---
title: ""
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
    - \usepackage{caption}
    - \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}

```{r setup, include=FALSE}
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
p_load(tidyverse, arrow, yaml, here, argparse, glue, knitr, kableExtra, scales, gridExtra, ggpubr)


# Working directory and command line argument setup
current_script = "generate_tables_and_figures/gen_payroll_outputs/src/print_payroll_tables.Rmd"
here::i_am(current_script)
source(here("R", "project_functions.R"))

task_dir = here(dirname(dirname(file.path(current_script))))

knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "OUT_WAGE_TABLE",
  "OUT_WAGE_PERCENTILES",
  "OUT_AVAILABLE_HOURS",
  "OUT_MAIN_TABLE",
  "OUT_APPENDIX_TABLE",
  "OUT_PCT_HOURS_TABLE"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()
  
timestamp <- get_timestamp()
```


\newpage
\blandscape

```{r}

#main table - only totals
in_table <- read_csv(cl_args$OUT_WAGE_TABLE) %>%
  filter(period == "total")

percentiles_table <- read_csv(cl_args$OUT_WAGE_PERCENTILES) %>%
  select(-period, -type) %>%
  mutate(across(where(is.numeric), ~round(.x,0)))

earnings_format <- dollar_format(prefix = "$", largest_with_cents = 0)

#combine stipend/training into one
payroll_table <- in_table %>% 
  mutate(cbt_training_earnings = training_earnings + stipend_earnings,
         cbt_training_hours = training_hours + stipend_hours) %>%
  arrange(desc(period)) %>%
  select(-n_payroll) %>%
  mutate(takeup_rate = round(takeup_rate*100,0) %>% paste0("%"),
         across(contains("hours") , ~round(.x,0)),
         across(contains("earnings"), ~earnings_format(.x)))

table_update <- payroll_table %>%
  left_join(percentiles_table, "pathway") %>%
  select(pathway, takeup_rate, qnt_25, qnt_50, qnt_75, regular_hours, cbt_training_hours, total_hours, total_earnings)
  

out_df <-  table_update  %>% 
  rename(path = pathway) %>% 
  mutate(path = case_when(path=="all" ~ "All Participants_1",
                          path=="cr" ~ "Outreach_3",
                          path=="ul" ~ "Algorithm_2",
                          path=="re" ~ "Re-entry_4")) %>%
  separate(path, into = c("path","path_order"), sep = "_") %>%
  arrange(path_order) %>%
  select(-path_order)

table <- out_df %>%
  kable(booktabs=T, longtable=T,
        col.names = c("", "Take-up Rate", "25th Percentile", "50th Percentile", "75th Percentile", "Average", "Average", "Average", "Average"),
        align=c("l", rep("c", 8)),
        ) %>% 
  kable_styling(font_size = 10) %>%
  add_header_above(c(" " = 2, "Work Hours" = 4, "CBT/Training\nHours" = 1, "Total\nHours" = 1, "Total\nEarnings" = 1)) %>%
  add_header_above(c(" " = 2, "Conditional on Take-up" = 7)) %>%

  column_spec(1, width="7em", latex_valign = 'm') %>%
  column_spec(2, width="4em", latex_valign = 'm') %>%
  column_spec(3:5, width="5em", latex_valign = 'm') %>%
  column_spec(6, width="3.5em", latex_valign = 'm') %>%
  column_spec(7, width="6em", latex_valign = 'm') %>%
  column_spec(8:9, width="3.5em", latex_valign = 'm') %>%
  add_indent(2:4)

table

writeLines(table, cl_args$OUT_MAIN_TABLE)
writeLines(table, str_replace(cl_args$OUT_MAIN_TABLE, ".tex", paste0("_",timestamp,".tex")))

```



```{r}

# appendix table
in_table <- read_csv(cl_args$OUT_WAGE_TABLE) %>%
  filter(period != "total")

earnings_format <- dollar_format(prefix = "$", largest_with_cents = 0)

#combine stipend/training into one
payroll_table <- in_table %>% 
  arrange(desc(period)) %>%
  select(-n_payroll) %>%
  mutate(takeup_rate = round(takeup_rate*100,0) %>% paste0("%"),
         across(contains("hours"), ~round(.x,0)),
         across(contains("earnings"), ~earnings_format(.x)))

out_df <-  payroll_table  %>% 
  rename(path = pathway) %>% 
  mutate(path = case_when(path=="all" ~ "All Participants_1",
                          path=="cr" ~ "Outreach_3",
                          path=="ul" ~ "Algorithm_2",
                          path=="re" ~ "Re-entry_4")) %>%
  mutate(period = case_when(period=="pre" ~ "Pre-COVID_1",
                            period=="standby" ~ "Standby Pay_2",
                            period=="post" ~ "Post-COVID_3")) %>%
  separate(path, into = c("path","path_order"), sep = "_") %>%
  separate(period, into = c("period","period_order"), sep = "_") %>%
  arrange(path_order,period_order) %>%
  select(-path_order, - period_order) %>%
  select(path, period, takeup_rate, 
         regular_earnings, regular_hours, training_earnings, training_hours, stipend_earnings, stipend_hours, total_earnings, total_hours)

table <- out_df %>%
  select(-path, -takeup_rate) %>%
  kable(booktabs=T, longtable=T,
        col.names = c("", rep(c("Earnings", "Hours"),4)),
        align=c("l", rep("c", 8))) %>% 
  kable_styling(font_size = 10) %>%
  add_header_above(c(" " = 1, "Work" = 2, "Trainings" = 2,"CBT/PD" = 2, "Total" = 2)) %>%
  column_spec(1, width="8em") %>%
  column_spec(2:9, width="3.5em") %>%
  add_indent(1:12) %>%
  group_rows("All Participants", 1, 3) %>%
  group_rows("Algorithm", 4, 6) %>%
  group_rows("Outreach", 7, 9) %>%
  group_rows("Re-entry", 10, 12) 


table

writeLines(table, cl_args$OUT_APPENDIX_TABLE)
writeLines(table, str_replace(cl_args$OUT_APPENDIX_TABLE, "up_to_date", timestamp))

```
\elandscape

```{r}
in_table <- read_csv(cl_args$OUT_AVAILABLE_HOURS)

out_df <- in_table %>%
  rename(path = pathway) %>%
  mutate(path = case_when(path=="all" ~ "All Participants_1",
                          path=="cr" ~ "Outreach_3",
                          path=="ul" ~ "Algorithm_2",
                          path=="re" ~ "Re-entry_4")) %>%
  separate(path, into = c("path","path_order"), sep = "_") %>%
  arrange(path_order) %>%
  select(-path_order) %>%
  mutate(pct = round(pct*100,1) %>% paste0(., "%"),
         across(starts_with("avg_"), ~round(.x,0)))


table <- out_df %>%
  kable(booktabs=T, longtable=T,
        col.names = c("", "Days to Take-Up", "Hours Worked", "Hours Possible", "Percent"),
        align=c("l", rep("c", 4))) %>% 
  kable_styling(font_size = 10) %>%
  add_indent(2:4) %>% 
  column_spec(2:5, latex_valign = "m")

table

writeLines(table, cl_args$OUT_PCT_HOURS_TABLE)

writeLines(table, str_replace(cl_args$OUT_PCT_HOURS_TABLE, "up_to_date", timestamp))
```